﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.ServiceModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using PmuRegistry.Silverlight.ModalDialogs;
using PmuRegistry.Silverlight.PmuRegistryDataServiceProxy;
using PmuRegistry.Silverlight.Utilities;
using System.Windows.Data;

namespace PmuRegistry.Silverlight.Pages.Devices
{
	public partial class Browse : Page
	{
		PhasorDataServiceClient m_client;
		ObservableCollection<Device> m_deviceList = new ObservableCollection<Device>();
		Dictionary<int, string> m_deviceStatuses = new Dictionary<int, string>();
		ActivityWindow m_activityWindow;

		public Browse()
		{
			InitializeComponent();
			m_client = Common.GetPhasorDataServiceClient();
			m_client.GetDeviceListCompleted += new EventHandler<GetDeviceListCompletedEventArgs>(client_GetDeviceListCompleted);
			m_client.GetDeviceStatusesCompleted += new EventHandler<GetDeviceStatusesCompletedEventArgs>(client_GetDeviceStatusesCompleted);
			m_client.SaveDeviceCompleted += new EventHandler<SaveDeviceCompletedEventArgs>(client_SaveDeviceCompleted);
			Loaded += new RoutedEventHandler(Browse_Loaded);
			ButtonSearch.Click += new RoutedEventHandler(ButtonSearch_Click);
			ButtonShowAll.Click += new RoutedEventHandler(ButtonShowAll_Click);
		}

		void client_SaveDeviceCompleted(object sender, SaveDeviceCompletedEventArgs e)
		{
			SystemMessages sm;
			if (e.Error == null)					
				sm = new SystemMessages(new Message() { UserMessage = e.Result, SystemMessage = string.Empty, UserMessageType = MessageType.Success },
						ButtonType.OkOnly);			
			else
			{
				if (e.Error is FaultException<CustomServiceFault>)
				{
					FaultException<CustomServiceFault> fault = e.Error as FaultException<CustomServiceFault>;
					sm = new SystemMessages(new Message() { UserMessage = fault.Detail.UserMessage, SystemMessage = fault.Detail.SystemMessage, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);
				}
				else
					sm = new SystemMessages(new Message() { UserMessage = "Failed to Save Device Information", SystemMessage = e.Error.Message, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);
			}
			sm.Show();
			m_client.GetDeviceListAsync();
		}

		void client_GetDeviceStatusesCompleted(object sender, GetDeviceStatusesCompletedEventArgs e)
		{
			if (e.Error == null)			
				m_deviceStatuses = e.Result;
			else
			{
				SystemMessages sm;
				if (e.Error is FaultException<CustomServiceFault>)
				{
					FaultException<CustomServiceFault> fault = e.Error as FaultException<CustomServiceFault>;
					sm = new SystemMessages(new Message() { UserMessage = fault.Detail.UserMessage, SystemMessage = fault.Detail.SystemMessage, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);
				}
				else
					sm = new SystemMessages(new Message() { UserMessage = "Failed to Retrieve Device Statuses", SystemMessage = e.Error.Message, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);

				sm.Show();
			}
		}

		void ButtonShowAll_Click(object sender, RoutedEventArgs e)
		{
			Storyboard sb = new Storyboard();
			sb = Application.Current.Resources["ButtonPressAnimation"] as Storyboard;
			sb.Completed += new EventHandler(delegate(object obj, EventArgs es) { sb.Stop(); });
			Storyboard.SetTarget(sb, ButtonShowAllTransform);
			sb.Begin();
			ListBoxDeviceList.ItemsSource = m_deviceList;
		}
		void ButtonSearch_Click(object sender, RoutedEventArgs e)
		{
			Storyboard sb = new Storyboard();
			sb = Application.Current.Resources["ButtonPressAnimation"] as Storyboard;
			sb.Completed += new EventHandler(delegate(object obj, EventArgs es) { sb.Stop(); });
			Storyboard.SetTarget(sb, ButtonSearchTransform);
			sb.Begin();
			string searchText = TextBoxSearch.Text.ToUpper();
			ListBoxDeviceList.ItemsSource = (from item in m_deviceList
											 where item.Acronym.ToUpper().Contains(searchText) || item.Name.ToUpper().Contains(searchText) || item.ProtocolName.ToUpper().Contains(searchText)
												|| item.InterconnectionName.ToUpper().Contains(searchText) || item.CompanyName.ToUpper().Contains(searchText) || item.VendorDeviceName.ToUpper().Contains(searchText)
											 select item).ToList();
		}
		void Browse_Loaded(object sender, RoutedEventArgs e)
		{
			m_activityWindow = new ActivityWindow("Loading Data... Please Wait...");
			m_activityWindow.Show();
		}
		void client_GetDeviceListCompleted(object sender, GetDeviceListCompletedEventArgs e)
		{
			if (e.Error == null)
			{
				m_deviceList = e.Result;
				PagedCollectionView devicesList = new PagedCollectionView(m_deviceList);
				ListBoxDeviceList.ItemsSource = devicesList;
				DataPagerDevices.Source = devicesList;
			}
			else
			{
				SystemMessages sm;
				if (e.Error is FaultException<CustomServiceFault>)
				{
					FaultException<CustomServiceFault> fault = e.Error as FaultException<CustomServiceFault>;
					sm = new SystemMessages(new Message() { UserMessage = fault.Detail.UserMessage, SystemMessage = fault.Detail.SystemMessage, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);
				}
				else
					sm = new SystemMessages(new Message() { UserMessage = "Failed to Retrieve Device List", SystemMessage = e.Error.Message, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);

				sm.Show();
			}
			if (m_activityWindow != null)
				m_activityWindow.Close();
		}
		
		// Executes when the user navigates to this page.
		protected override void OnNavigatedTo(NavigationEventArgs e)
		{
			m_client.GetDeviceListAsync();
			m_client.GetDeviceStatusesAsync();
		}

		private void ComboboxStatus_Loaded(object sender, RoutedEventArgs e)
		{
			if (m_deviceStatuses.Count > 0)
			{
				ComboBox statuses = ((ComboBox)sender);
				statuses.ItemsSource = m_deviceStatuses;
				//if (statuses.Items.Count > 0)
				//    statuses.SelectedIndex = 0;
				try
				{
					Device device = new Device();
					device = statuses.DataContext as Device;
					foreach (KeyValuePair<int, string> item in m_deviceStatuses)
					{
						if (item.Key == device.StatusID)
						{
							statuses.SelectedItem = item;
							break;
						}
					}
				}
				catch
				{
					//we dont care.
				}
			}
		}

		private void HyperlinkButton_Click(object sender, RoutedEventArgs e)
		{
			string deviceId = ((HyperlinkButton)sender).Tag.ToString();
			NavigationService.Navigate(new Uri("/Pages/Devices/AddNew.xaml?did=" + deviceId, UriKind.Relative));
		}

		private void HyperlinkButtonPhasors_Click(object sender, RoutedEventArgs e)
		{
			int deviceId = Convert.ToInt32(((HyperlinkButton)sender).Tag.ToString());
			string acronym = ((HyperlinkButton)sender).Name;
			Phasors phasors = new Phasors(deviceId, acronym);
			phasors.Show();
		}

		private void HyperlinkButtonMeasurements_Click(object sender, RoutedEventArgs e)
		{
			string deviceId = ((HyperlinkButton)sender).Tag.ToString();
			NavigationService.Navigate(new Uri("/Pages/Manage/Measurements.xaml?did=" + deviceId, UriKind.Relative));
		}

		private void ButtonSave_Click(object sender, RoutedEventArgs e)
		{
			Button saveButton = ((Button)sender);
			Device device = new Device();
			device = saveButton.DataContext as Device;
			m_client.SaveDeviceAsync(device, false, 0, 0);
			
		}

		private void ComboboxStatus_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			//(((ComboBox)sender).DataContext as Device).StatusID = ((KeyValuePair<int, string>)((ComboBox)sender).SelectedItem).Key;
		}	
	}
}
